﻿using System;
using System.Configuration;
using System.Web.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Reflection;
using Alex.Library.Web.Ajax.Exceptions;

namespace Alex.Library.Web.Ajax
{
    /// <summary>
    /// 生成Ajax客户端脚本的HttpHandler
    /// </summary>
    public class AjaxClientScriptHandler : IHttpHandler
    {
        /// <summary>
        /// IHttpHandler方法
        /// </summary>
        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// 是否是在Debug模式下使用
        /// </summary>
        /// <returns></returns>
        private bool CompilationIsInDebug()
        {
            CompilationSection ds = (CompilationSection)ConfigurationManager.GetSection("system.web/compilation");
            return ds.Debug;
        }

        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="context">Http上下文</param>
        public void ProcessRequest(HttpContext context)
        {
            if (!CompilationIsInDebug())
            {
                throw new Exception("只能在调试模式下使用此类.");
            }
            //如果没有任何参数表示输出页面                        
            if (context.Request.Form.Count == 0)
            {
                context.Response.Charset = "utf-8";
                context.Response.ContentEncoding = Encoding.UTF8;
                context.Response.ContentType = "text/html";
                string assemblyName = System.Reflection.Assembly.GetCallingAssembly().FullName;
                IAjaxScriptPageHandler scriptPage = AjaxScriptPageHandler.EvalTemplate(context.Request.Path,
                    "", "", "");
                string _PageContent = scriptPage.GetPageContent();
                context.Response.Write(_PageContent);
                context.Response.End();
            }
            else if (!String.IsNullOrEmpty(context.Request["getType"]))
            {
                if (context.Request["getType"] == "1") //获取类方法
                {
                    context.Response.Charset = "utf-8";
                    context.Response.ContentEncoding = Encoding.UTF8;
                    context.Response.ContentType = "text/html";
                    IAjaxScriptPageHandler scriptPage = null;
                    try
                    {
                        string methodHtml = GetMethodsHtml(ObjectMethodHandler.GetMethods(context.Request["txtClassName"]));
                        scriptPage = AjaxScriptPageHandler.EvalTemplate(context.Request.Path,
                        context.Request["txtClassName"], methodHtml, "");
                    }
                    catch (ClassNotFoundException cex)
                    {
                        scriptPage = AjaxScriptPageHandler.EvalTemplate(context.Request.Path,
                        context.Request["txtClassName"], "", "alert('" + cex.Message + "');");
                    }
                    catch (Exception ex)
                    {
                        scriptPage = AjaxScriptPageHandler.EvalTemplate(context.Request.Path,
                        context.Request["txtClassName"], "", "alert('" + ex.Message + "');");
                    }

                    string _PageContent = scriptPage.GetPageContent();
                    context.Response.Write(_PageContent);
                    context.Response.End();
                }
                else //生成脚本
                {
                    string fileName = context.Request["txtClassName"] + ".as.js";
                    context.Response.Charset = "utf-8";
                    context.Response.ContentEncoding = Encoding.UTF8;
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                    string[] methodNames = context.Request["MethodName"].Split(',');
                    IAjaxScriptPageHandler scriptPage = AjaxScriptPageHandler.EvalCreateScript(context.Request["txtClassName"], methodNames);
                    byte[] buffer = Encoding.UTF8.GetBytes(scriptPage.GetPageContent());
                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    context.Response.Flush();
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Charset = "utf-8";
                context.Response.ContentEncoding = Encoding.UTF8;
                context.Response.ContentType = "text/html";
                IAjaxScriptPageHandler scriptPage = AjaxScriptPageHandler.EvalTemplate(context.Request.Path,
                    "", "", "alert('传递的参数错误');");
                string _PageContent = scriptPage.GetPageContent();
                context.Response.Write(_PageContent);
                context.Response.End();
            }
        }

        /// <summary>
        /// 获取类方法的Html页面
        /// </summary>
        /// <param name="methods">类方法数组</param>
        /// <returns>类方法的Html页面</returns>
        private string GetMethodsHtml(MethodInfo[] methods)
        {
            return AjaxScriptPageHandler.EvalMethodHtml(methods).GetPageContent();
        }
    }
}
